package com.conversationboard.controller.poll;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.VoterCache;
import com.conversationboard.model.NoSuchThreadException;
import com.conversationboard.model.Poll;
import com.conversationboard.model.Thread;

@WebServlet(name = "VoteControllerServlet", urlPatterns = "/VoteControllerServlet")
public class VoteControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -6532286511607643353L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String loginId = request.getUserPrincipal().getName();
		int boardId = Integer.parseInt(request.getParameter("boardId"));
		int threadId = Integer.parseInt(request.getParameter("threadId"));
		String selectedOption = request.getParameter("optionid");

		if (selectedOption == null) {
			request.setAttribute("message", "Please select something to vote for.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);
			return;
		}

		if (VoterCache.hasAlreadyVoted(loginId, boardId, threadId)) {
			request.setAttribute("message", "You have already voted in this poll and cannot vote again.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);
			return;
		}

		try {

			/*
			 * Make sure users don't construct URLs to vote in polls after
			 * they've closed.
			 */

			Thread thread = Thread.get(boardId, threadId);

			Date closingDate = thread.getPollClosingDate();
			Date today = new Date();

			if (!closingDate.after(today)) {
				request.setAttribute("message", "This poll has closed.");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			int optionId = Integer.parseInt(selectedOption);

			/*
			 * Register the vote and then add the user to the list of users who
			 * cannot vote again
			 */

			Poll.vote(boardId, threadId, optionId);

			VoterCache.addVote(loginId, boardId, threadId, optionId);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/ThreadSelectedControllerServlet?boardid=" + boardId + "&threadid=" + threadId);
			dispatcher.forward(request, response);

		} catch (NoSuchThreadException e) {
			/* Do Nothing */
		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}
